from django.shortcuts import render
from django.http import HttpResponseRedirect,HttpResponse
from django.contrib.auth.decorators import user_passes_test, login_required
from django.contrib.auth.models import User
from django.contrib import auth
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from management.models import MyUser, Img, Group, Table,BaseMap
from django.core.urlresolvers import reverse, reverse_lazy
from management.utils import permission_check
from django.core import serializers



def index(request):
    user = request.user if request.user.is_authenticated() else None
    content = {
        'active_menu': 'homepage',
        'user': user,
    }
    return render(request, 'management/index.html', content)

def carto(request):
    user = request.user if request.user.is_authenticated() else None
    content = {
        'active_menu': 'cartopage',
        'group_list': Group.objects.all(),
        'user': user,
        'basemap_json':serializers.serialize('json',BaseMap.objects.all()),
        'basemap_list':BaseMap.objects.all()
    }
    return render(request, 'management/carto_page.html', content)


def signup(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('homepage'))
    state = None
    if request.method == 'POST':
        password = request.POST.get('password', '')
        repeat_password = request.POST.get('repeat_password', '')
        if password == '' or repeat_password == '':
            state = 'empty'
        elif password != repeat_password:
            state = 'repeat_error'
        else:
            username = request.POST.get('username', '')
            if User.objects.filter(username=username):
                state = 'user_exist'
            else:
                new_user = User.objects.create_user(username=username, password=password,
                                                    email=request.POST.get('email', ''))
                new_user.save()
                new_my_user = MyUser(user=new_user, nickname=request.POST.get('nickname', ''))
                new_my_user.save()
                state = 'success'
    content = {
        'active_menu': 'homepage',
        'state': state,
        'user': None,
    }
    return render(request, 'management/signup.html', content)


def login(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('homepage'))
    state = None
    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            auth.login(request, user)
            return HttpResponseRedirect(reverse('homepage'))
        else:
            state = 'not_exist_or_password_error'
    content = {
        'active_menu': 'homepage',
        'state': state,
        'user': None
    }
    return render(request, 'management/login.html', content)


def logout(request):
    auth.logout(request)
    return HttpResponseRedirect(reverse('homepage'))


@login_required(login_url=reverse_lazy('login'))
def set_password(request):
    user = request.user
    state = None
    if request.method == 'POST':
        old_password = request.POST.get('old_password', '')
        new_password = request.POST.get('new_password', '')
        repeat_password = request.POST.get('repeat_password', '')
        if user.check_password(old_password):
            if not new_password:
                state = 'empty'
            elif new_password != repeat_password:
                state = 'repeat_error'
            else:
                user.set_password(new_password)
                user.save()
                state = 'success'
        else:
            state = 'password_error'
    content = {
        'user': user,
        'active_menu': 'homepage',
        'state': state,
    }
    return render(request, 'management/set_password.html', content)


@user_passes_test(permission_check, login_url=reverse_lazy('login'))
def add_group(request):
    user = request.user
    state = None
    if request.method == 'POST':
        new_group = Group(
            name=request.POST.get('name', ''),
            # info=request.POST.get('info',''),
            author=user.username,
            category=request.POST.get('category', ''),
            # price=request.POST.get('price', 0),
            publish_date=request.POST.get('publish_date', '')
        )
        new_group.save()
        state = 'success'
    content = {
        'user': user,
        'active_menu': 'add_group',
        'state': state,
    }
    return render(request, 'management/add_group.html', content)


def view_group_list(request):
    user = request.user if request.user.is_authenticated() else None
    category_list = Group.objects.values_list('category', flat=True).distinct()
    query_category = request.GET.get('category', 'all')
    if (not query_category) or Group.objects.filter(category=query_category).count() is 0:
        query_category = 'all'
        group_list = Group.objects.all()
    else:
        group_list = Group.objects.filter(category=query_category)

    if request.method == 'POST':
        keyword = request.POST.get('keyword', '')
        group_list = Group.objects.filter(name__contains=keyword)
        query_category = 'all'

    paginator = Paginator(group_list, 10)
    page = request.GET.get('page')
    try:
        group_list = paginator.page(page)
    except PageNotAnInteger:
        group_list = paginator.page(1)
    except EmptyPage:
        group_list = paginator.page(paginator.num_pages)
    content = {
        'user': user,
        'active_menu': 'view_group',
        'category_list': category_list,
        'query_category': query_category,
        'group_list': group_list,
    }
    return render(request, 'management/view_group_list.html', content)


def detail(request):
    user = request.user if request.user.is_authenticated() else None
    group_id = request.GET.get('id', '')
    if group_id == '':
        return HttpResponseRedirect(reverse('view_book_list'))
    try:
        group = Group.objects.get(pk=group_id)
    except Group.DoesNotExist:
        return HttpResponseRedirect(reverse('view_group_list'))
    content = {
        'user': user,
        'active_menu': 'view_group',
        'group': group,
    }
    return render(request, 'management/detail.html', content)


@user_passes_test(permission_check, login_url=reverse_lazy('login'))
def add_img(request):
    user = request.user
    state = None
    if request.method == 'POST':
        try:
            new_img = Img(
                name=request.POST.get('name', ''),
                description=request.POST.get('description', ''),
                img=request.FILES.get('img', ''),
                img_md=request.FILES.get('img_md',''),
                group=Group.objects.get(pk=request.POST.get('group', ''))
            )
            new_img.save()
        except Group.DoesNotExist as e:
            state = 'error'
            print(e)
        else:
            state = 'success'
    content = {
        'user': user,
        'state': state,
        'group_list': Group.objects.all(),
        'active_menu': 'add_img',
    }
    return render(request, 'management/add_img.html', content)


@user_passes_test(permission_check, login_url=reverse_lazy('login'))
def add_table(request):
    user = request.user
    state = None
    if request.method == 'POST':
        try:
            new_table = Table(
                name=request.POST.get('name', ''),
                description=request.POST.get('description', ''),
                file=request.FILES.get('table', ''),
                group=Group.objects.get(pk=request.POST.get('group', ''))
            )
            new_table.save()
        except Group.DoesNotExist as e:
            state = 'error'
            print(e)
        else:
            state = 'success'
    content = {
        'user': user,
        'state': state,
        'group_list': Group.objects.all(),
        'active_menu': 'add_table',
    }
    return render(request, 'management/add_table.html', content)

def getTables(request):
    group_id = request.GET.get('group_id', '')
    tables=None
    if group_id=='':return
    group_id=int(group_id)
    try:
        group = Group.objects.get(pk=group_id)
        tables=Table.objects.filter(group=group)
    except Group.DoesNotExist:
        return
    return HttpResponse(serializers.serialize('json',tables))
#Not used
def getFileInfo(request):
    url = "./media/" + request.GET["url"]
    # url = url.decode("gbk")
    a = open(url)
    text=a.read()
    a.close()
    return HttpResponse(text.decode("gbk"))

@user_passes_test(permission_check, login_url=reverse_lazy('login'))
def add_basemap(request):
    user = request.user
    state = None
    if request.method == 'POST':
        try:
            new_basemap=BaseMap(
                name=request.POST.get('name',''),
                file=request.FILES.get('file',''),
                scale=request.POST.get('scale',''),
                type=request.POST.get('type',''),
                projection=request.POST.get('projection',''),
                grade=request.POST.get('grade',''),
                area=request.POST.get('area','')
            )
            new_basemap.save()
        except Exception:
            state='error'
        else:
            state='success'
    content = {
        'user': user,
        'state': state,
        'group_list': Group.objects.all(),
        'active_menu': 'add_basemap',
        }
    return render(request, 'management/add_basemap.html', content)

